// 员工
<template>
  <div class="employees-container">
    <div class="dashboard">
      <PageTools :show-before="true">
        <span slot="before" type="primary">共{{ page.total }}条记录</span>
        <template v-slot:after>
          <el-button size="small" type="success" @click="$router.push('/import')">excel导入</el-button>
          <el-button size="small" type="danger" @click="output">excel导出</el-button>
          <el-button
            size="small"
            type="primary"
            @click="showDialog = true"
            :disabled="!checkPermission('POINT-USER-ADD')"
          >
            新增员工
          </el-button>
        </template>
      </PageTools>
      <!-- 表格组建 -->
      <el-table v-loading="loading" border stripe :data="list">
        <el-table-column label="序号" sortable="" type="index" />
        <el-table-column prop="username" label="姓名" sortable="" />
        <el-table-column label="头像" sortable="" align="center">
          <template v-slot="{ row }">
            <img
              v-imagerror="defaultImg"
              :src="row.staffPhoto ? row.staffPhoto : ''"
              alt=""
              style="border-radius: 50%; width: 40px; height: 40px; margin: 10px"
              @click="showQrCode(row.staffPhoto)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="workNumber" label="工号" sortable="" />
        <el-table-column prop="formOfEmployment" label="聘用形式" sortable="" :formatter="formatEmployment" />
        <el-table-column prop="departmentName" label="部门" sortable="" />
        <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
          <template slot-scope="obj">
            {{ obj.row.timeOfEntry | formatDate }}
          </template>
        </el-table-column>
        <el-table-column prop="enableState" label="账户状态" sortable="">
          <template v-slot="{ row }">
            <el-switch :value="row.enableState === 1" active-color="#13ce66" inactive-color="#ff4949" />
          </template>
        </el-table-column>
        <el-table-column label="操作" sortable="" fixed="right" width="280">
          <template v-slot="{ row }">
            <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
            <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination
          :current-page="page.page"
          :page-size="page.size"
          :total="page.total"
          layout="total,sizes,prev,pager,next"
          :page-sizes="[2, 5, 10, 15]"
          @current-change="changPage"
          @size-change="changeSize"
        />
      </el-row>
      <!-- 添加员工弹出层 -->
      <AddEmployee :show-dialog.sync="showDialog" />
      <!-- 二维码弹出层 -->
      <el-dialog title="二维码" :visible.sync="showCodeDialog" @close="imgUrl = ''">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 添加角色弹出层 -->
      <AssignRole ref="roleDialog" :show-role-dialog.sync="showDialogRole" :user-id="userId" />
    </div>
  </div>
</template>
<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'

export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      list: [],
      page: {
        page: 1,
        size: 5,
        total: 0
      },
      loading: false,
      showDialog: false,
      defaultImg: require('@/assets/common/head.jpg'),
      showCodeDialog: false,
      showDialogRole: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page)
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    changPage(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    changeSize(newSize) {
      this.page.size = newSize
      this.getEmployeeList()
    },
    // 格式化 聘用形式
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployEnum.hireType.find((item) => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm('确认删除该员工么？')
        if (this.list.length === 1) {
          this.page.page > 1 ? this.page.page-- : this.page.page
        }
        await delEmployee(id)
        this.$message.success('删除员工成功！')
        this.getEmployeeList()
      } catch (error) {
        this.$message.denger('删除员工失败！')
      }
    },
    // 导出excel
    async output() {
      // 用于英文转中文
      const headers = {
        姓名: 'username',
        手机号: 'mobile',
        工号: 'workNumber',
        部门: 'departmentName',
        聘用形式: 'formOfEmployment',
        入职日期: 'timeOfEntry',
        转正日期: 'correctionTime'
      }
      // 获取所有的员工列表数据
      const { rows } = await getEmployeeList({
        page: 1,
        // size: 20
        size: this.page.total
      })
      const data = this.formatJson(rows, headers)
      // 懒加载 插件
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头信息
          data, // 导出的具体数据  [['张三',001,'正式','采购部',...],['李四',002,'正式','开发部',...]]
          filename: '员工信息表', // 导出的文件名
          autoWidth: true, // 是否自定义宽度
          bookType: 'xlsx', // 导出文件类型
          multiHeader: [['员工信息表', '', '', '', '', '', '']], // 复杂表头的导出
          merges: ['A1:G1'] // 需要合并的部分
        })
      })
    },
    // 转换数据 [{name:'张三',mobile：123}]  ->  [[张三，123]]
    formatJson(rows, headers) {
      return rows.map((obj) =>
        Object.keys(headers).map((item) => {
          if (headers[item] === 'timeOfEntry' || headers[item] === 'correctionTime') {
            return formatDate(obj[headers[item]])
          }
          if (headers[item] === 'formOfEmployment') {
            var OBJ = EmployEnum.hireType.find((key) => key.id === obj[headers[item]])
            return OBJ ? OBJ.value : '未知'
          }

          return obj[headers[item]]
        })
      )
    },
    // 生成二维码
    showQrCode(url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    async editRole(id) {
      this.userId = id
      await this.$refs.roleDialog.getRoleById(id)
      this.showDialogRole = true
    }
  }
}
</script>

<style scoped lang="scss">
.employees-container {
  padding: 15px;
}
</style>
